package hanhns.test.listview;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.ArrayList;

import hanhns.test.R;
import hanhns.test.provider_database.BNoteProvider;

public class ListNoteUseSimpleCursorAdapter extends ListActivity implements android.view.View.OnClickListener{
/** Called when the activity is first created. */
	
	private static String TAG = "ListNoteUseSimpleCursorAdapter";
	
	public static ArrayList<Integer> arrayChecked;
	// Menu item ids
    public static final int MENU_ITEM_DELETE = Menu.FIRST;
    public static final int MENU_ITEM_INSERT = Menu.FIRST + 1;
    public static final int MENU_ITEM_UPDATE = Menu.FIRST + 3;
    
    private static Button search;
    private static EditText key;
    private Cursor cursor;
    private static LinearLayout deleteLayout;
    private static Button deleteButton;
    
    //cot "title" la 1
    private static final int COLUMN_INDEX_TITLE = 1;
    
    // danh sach cac colums
	private static final String[] COLUMNS = new String[] {
        BNoteProvider._ID_COLUMN, // 0
        BNoteProvider.NOTE_TITLE_COLUMN, // 1
        BNoteProvider.NOTE_CONTENT_COLUMN  // 2
	};
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_note_test);
        Log.e(TAG, "oncreat");
        
        search = (Button) findViewById(R.id.button_search);
        search.setOnClickListener(this);
        key = (EditText) findViewById(R.id.search_note_edittext);
        arrayChecked = new ArrayList<Integer>();
        deleteButton = (Button) findViewById(R.id.deleteButon);
        deleteLayout = (LinearLayout) findViewById(R.id.delete_layout);
        
        // If no data was given in the intent call this activity.
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(BNoteProvider.CONTENT_URI);
        }  
        
        //gan' Context menu vao list
        getListView().setOnCreateContextMenuListener(this);
        
        // Perform a managed query. The Activity will handle closing and requerying the cursor
        // when needed.
        cursor = managedQuery(BNoteProvider.CONTENT_URI, COLUMNS, null,
        		null, BNoteProvider.NOTE_TITLE_COLUMN);
        //startManagingCursor(cursor); //khong can thiet vi da su dung ham managedQuery cua Activity.
        
       
        show(cursor);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        // This is our one standard application action -- inserting a
        // new note into the list.
        menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_add_new_note)
               // .setShortcut('3', 'a') /*khong can thiet*/
                .setIcon(android.R.drawable.ic_menu_add);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ITEM_INSERT:
            // Launch activity to insert a new item
            startActivity(new Intent(Intent.ACTION_INSERT, getIntent().getData()));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    // cac thanh phan trong context menu
    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    	
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return;
        }

        Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
        if (cursor == null) {
            // For some reason the requested item isn't available, do nothing
            return;
        }

        // Setup the menu header
        menu.setHeaderTitle(cursor.getString(COLUMN_INDEX_TITLE));

        // Add a menu item to delete the note
        menu.add(0, MENU_ITEM_DELETE, 0, R.string.menu_delete);
        menu.add(0, MENU_ITEM_UPDATE, 0, R.string.menu_update);
        
    }
        
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info;
        try {
             info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        } catch (ClassCastException e) {
            Log.e(TAG, "bad menuInfo", e);
            return false;
        }
        
        //uri for note selected
        Uri noteUri = ContentUris.withAppendedId(getIntent().getData(), info.id);
        switch (item.getItemId()) {
            case MENU_ITEM_DELETE: {
                // Delete the note that the context menu is for
            	int count;
                count = getContentResolver().delete(noteUri, null, null);
                if(count>0)
                Toast.makeText(getApplicationContext(), "Deleted " + String.valueOf(count)
                		+ " note ", Toast.LENGTH_SHORT).show();
                return true;
            }
            case MENU_ITEM_UPDATE: {
            	startActivity(new Intent(Intent.ACTION_EDIT, noteUri));
            	return true;
            }
        }
        return false;
    }

    
    // su kien khi kick vao mot item trong list
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	Toast.makeText(this, "click", Toast.LENGTH_SHORT).show();
    	Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
    	startActivity(new Intent(Intent.ACTION_VIEW, uri));
//        String action = getIntent().getAction();
//        if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
//            // The caller is waiting for us to return a note selected by
//            // the user.  The have clicked on one, so return it now.
//            setResult(RESULT_OK, new Intent().setData(uri));
//        } else {
//            // Launch activity to view/edit the currently selected item
//            startActivity(new Intent(Intent.ACTION_EDIT, uri));
//        }
    }

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
			case R.id.button_search: 
				String StrKey = key.getText().toString();
				String selection = "title like '%" + StrKey + "%' or content like'%" + StrKey + "%'";
				cursor = managedQuery(BNoteProvider.CONTENT_URI, COLUMNS, selection, null, BNoteProvider.NOTE_TITLE_COLUMN);
				Log.e(TAG, "number result of search is: " + cursor.getCount());
				show(cursor);
				InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(key.getWindowToken(), 0);
				
				break;
			default:
				break;
		}
	}
	
	 // Used to map notes from the cursor to views
	private void show(Cursor cursor){
		CusTomSimpleCurSorAdapter simpleCusorAdapter = new CusTomSimpleCurSorAdapter(this, R.layout.note_row, cursor,
				new String[] { BNoteProvider.NOTE_TITLE_COLUMN, BNoteProvider.NOTE_CONTENT_COLUMN},
                new int[] { R.id.titleNote, R.id.contentNote });
		setListAdapter(simpleCusorAdapter);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		arrayChecked.clear();
//		Toast.makeText(this, "destroy", Toast.LENGTH_SHORT).show();
		super.onDestroy();
		
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
//		Toast.makeText(this, "onconfigurationChanged", Toast.LENGTH_SHORT).show();
//		havecheck();
		super.onConfigurationChanged(newConfig);
	}
	
	public static void havecheck(){
		int totalChecked = arrayChecked.size();
		if(totalChecked > 0){
//			Toast.makeText(this, "have note checked!", Toast.LENGTH_SHORT).show();
			deleteLayout.setVisibility(View.VISIBLE);
			deleteButton.setText("Detete (" + totalChecked + ")");
		} else {
//			Toast.makeText(this, "don't have note checked!", Toast.LENGTH_SHORT).show();
			deleteLayout.setVisibility(View.GONE);
		}
	}
}
